package com.yy.micro.magic.ext.strategy.format;

import com.yy.micro.magic.core.annotation.Strategy;
import com.yy.micro.magic.core.model.RuleDescriptor;
import com.yy.micro.magic.core.model.RuntimeMetadata;
import com.yy.micro.magic.core.strategy.RuleStrategyAdapter;

import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Strategy("dateFormat")
public class DateFormatStrategy extends RuleStrategyAdapter {

    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private Map<String,SimpleDateFormat> formatMap = new ConcurrentHashMap<>();
    @Override
    protected void process(final RuntimeMetadata metadata) {
        Object value = metadata.getInputValue();
        RuleDescriptor rule = metadata.getRule();
        Date date  = null;
        if (value instanceof Date){
            date = (Date) value;
        }else if (value instanceof  String){
            try {
                String fromFormat = rule.getFromFormat();
                if (StringUtils.isEmpty(fromFormat)){
                    fromFormat = DEFAULT_FORMAT;
                }
                SimpleDateFormat sdf = getSimpleDateFormat(fromFormat);
                date = sdf.parse(value.toString());
            } catch (ParseException e) {
                logger.warn("Pare date["+value+"] exception !",e);
            }
        }
        if (null != date){
            String format = rule.getFormat();
            if (StringUtils.isEmpty(format)){
                format = DEFAULT_FORMAT;
            }
            SimpleDateFormat sdf = getSimpleDateFormat(format);
            String str = sdf.format(date);
            addTempResult(rule.getName(),str);
        }else {
            addResult(null);
            logger.warn("Format  date is null !");
        }
    }

    private SimpleDateFormat getSimpleDateFormat(String format){
        SimpleDateFormat dateFormat = null;
        if (formatMap.containsKey(format)){
            dateFormat = formatMap.get(format);
        }else {
            dateFormat=new SimpleDateFormat(format);
            formatMap.put(format,dateFormat);
        }
        return dateFormat;
    }
}
